<?php !defined( 'SUNCMS' ) && exit( 'No direct script access allowed'  );

/**
 * 
 * Sun CMS
 * 
 * @author			Burning
 * @copyright		Copyright (c) 2009, IsunCms.Com.
 * @license			http://www.isuncms.com/license.htm
 * @link				http://www.isuncms.com/
 * @since				Version 1.0 Beta
 * 
 */


//显示登录页面
if( $do == 'index' )
{
	include( display( 'login' ) );
}
//登录
elseif( $do == 'login' )
{
	$login_times = get_cookie( 'login_times' );
	$login_times = empty( $login_times['login_times'] )?0:$login_times['login_times'];
	if( $login_times >= 10 )
	{
		alert( '登录错误超过10次，该IP已被锁定，15分钟内不得登录！' );
		go_url( SITE_URL.SCRIPT_NAME );
		exit;
	}
	$authcode = get_post( 'authcode' );
	$authcode_true = get_cookie( 'authcode' );
	if( strtolower( $authcode ) != strtolower( $authcode_true['authcode'] ) )
	{
		alert( '验证码错误！' );
		go_url( SITE_URL.SCRIPT_NAME );
		exit;
	}
	$username = get_post( 'username' );
	$password = get_post( 'password' );
	$password = md5( $password );
	$sql = "SELECT `a`.`password`, `a`.`id`, `a`.`group_id`, `b`.`name` FROM `".DB_PRE."member` as `a`
			LEFT JOIN `".DB_PRE."membergroup` as `b` ON `a`.`group_id` = `b`.`id` AND `b`.`type` = 'admin' 
			WHERE `a`.`username` = '{$username}'";
	$return = $db->query( $sql, true );
	if( empty( $return ) )
	{
		set_cookie( 'login_times', array( 'login_times' => $login_times+1, 'time' => 900 ) );
		alert( '没有此用户！' );
		go_url( SITE_URL.SCRIPT_NAME );
		exit;
	}
	if( $return['password'] !== $password )
	{
		set_cookie( 'login_times', array( 'login_times' => $login_times+1, 'time' => 900 ) );
		alert( '用户名或密码错误！' );
		go_url( SITE_URL.SCRIPT_NAME );
		exit;
	}
	$update_sql = "UPDATE `".DB_PRE."memberdata` SET `last_login_time` = '".TIME."' , `login_times` = `login_times`+1 ,`last_login_ip` = '".IP."' WHERE `uid` = '{$return['id']}'";
	$db->execute( $update_sql );
	$datas = array
	(
			'admin' => 1,
			'username' => $username,
			'password' => $password,
			'user_id' => $return['id'],
			'group_id' => $return['group_id'],
			'time' => 1800
	);
	set_cookie( 'slogin', $datas, 1 );
	unset( $username, $password, $sql, $return, $datas );
	$forward = get_cookie( 'current_url' );
	isset( $forward['url'] )?go_url( $forward['url'] ):go_url( SITE_URL.SCRIPT_NAME );
	unset_cookie( array( 'current_url', 'login_times', 'authcode' ) );
}
elseif( $do == 'logout' )
{
	unset_cookie( array( 'slogin' ) );
	go_url( SITE_URL );
}